package com.sumainfor.pc.market.service;

import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.ActivityMapper;
import com.sumainfor.pc.market.dao.UtilsMapper;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 功能描述:
 * 活动
 * @Auther: zhlu
 * @Date: 2019/2/15 17:06
 * @Description:
 */
@Service
public class ActivityServiceImpl {
    Logger log= LoggerFactory.getLogger(ActivityServiceImpl.class);
    private ReentrantLock lock = new ReentrantLock(false);

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    ActivityMapper activityMapper;

    String UUID=null;

    String FuId=null;
    String PayId=null;
    String SenId=null;
    String FirId=null;

    /**
     * 功能描述: 
     * 创建活动
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/2/15 17:10
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean   AddActivity(Map<String,Object> params){
        boolean result=false;
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            try {
                //查询房源编号
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "ActId");
                    put("database", Constants.DATA_SOURCE_TCMKT);
                    put("surface", "tcmkt_activity");
                }});
                if(uuid!=null){
                    int number=Integer.valueOf(uuid.get("uuid").toString());
                    UUID= ComUtils.getLocalTrmSeqNum("hd",number);
                }else{
                    UUID=ComUtils.getLocalTrmSeqNum("hd",0);
                }
                //所有新增处理
                Map<String,Object>commonInsertParms=new HashMap<String,Object>();
                commonInsertParms.put("by", ContextUtils.getUserId());//操作人
                commonInsertParms.put("ActId",UUID);//活动主表编号
                commonInsertParms.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                commonInsertParms.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(commonInsertParms);

                //支付渠道      0.线上/转账支付    1.渠道支付
                if(params.get("PayType").equals(0)){
                    params.put("LoaId",null);
                }
                if(params.get("IfLong").equals(false)){
                    params.put("IfLong",0);
                }else{
                    params.put("IfLong",1);
                }
                if(params.get("IfCoupon").equals(false)){
                    params.put("IfCoupon",0);
                }else{
                    params.put("IfCoupon",1);
                }
                log.info("IfLong------------"+params.get("IfLong"));
                log.info("params------------"+params);
                //新增收房资料
                params.putAll(commonInsertParms);
                activityMapper.AddActivity(params);

                //活动-满减（折扣）
                List<Map<String, Object>> full = (List<Map<String, Object>>) params.get("full");
                for(Map<String, Object> map:full){
                    if(map.get("checkbox").equals(true)){
                        //活动-满减（折扣）
                        Map<String,Object>fuId=utilsMapper.getUUID(new HashMap<String,Object>(){{
                            put("uuid", "FuId");
                            put("database", Constants.DATA_SOURCE_TCMKT);
                            put("surface", "tcmkt_activity_full");
                        }});
                        if(fuId!=null){
                            int number=Integer.valueOf(fuId.get("uuid").toString());
                            FuId= ComUtils.getLocalTrmSeqNum("hdzk",number);
                        }else{
                            FuId=ComUtils.getLocalTrmSeqNum("hdzk",0);
                        }
                        map.putAll(commonInsertParms);
                        map.put("FuId",FuId);
                        map.put("ActType",1);
                        activityMapper.AddActivityFull(map);
                    }
                }

                //活动-付款方式（付款周期）
                List<Map<String, Object>> pay = (List<Map<String, Object>>) params.get("pay");
                for(Map<String, Object> map:pay){
                    if(map.get("checkbox").equals(true)){
                        //活动-付款方式（付款周期）
                        Map<String,Object>payId=utilsMapper.getUUID(new HashMap<String,Object>(){{
                            put("uuid", "PayId");
                            put("database", Constants.DATA_SOURCE_TCMKT);
                            put("surface", "tcmkt_activity_pay");
                        }});
                        if(payId!=null){
                            int number=Integer.valueOf(payId.get("uuid").toString());
                            PayId= ComUtils.getLocalTrmSeqNum("hdzq",number);
                        }else{
                            PayId=ComUtils.getLocalTrmSeqNum("hdzq",0);
                        }
                        map.putAll(commonInsertParms);
                        map.put("PayId",PayId);
                        map.put("ActType",2);
                        activityMapper.AddActivityPay(map);
                    }
                }
                //活动-满送
                Map<String, Object> send = (Map<String, Object>) params.get("send");
                if(send.get("checkbox").equals(true)){
                    //活动-满送
                    Map<String,Object>senId=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "SenId");
                        put("database", Constants.DATA_SOURCE_TCMKT);
                        put("surface", "tcmkt_activity_send");
                    }});
                    if(senId!=null){
                        int number=Integer.valueOf(senId.get("uuid").toString());
                        SenId= ComUtils.getLocalTrmSeqNum("hdms",number);
                    }else{
                        SenId=ComUtils.getLocalTrmSeqNum("hdms",0);
                    }
                    send.putAll(commonInsertParms);
                    send.put("SenId",SenId);
                    send.put("ActType",3);
                    activityMapper.AddActivitySend(send);
                }

                //活动-首月
                Map<String, Object> first = (Map<String, Object>) params.get("first");
                if(first.get("checkbox").equals(true)){
                    //活动-首月
                    Map<String,Object>firId=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "FirId");
                        put("database", Constants.DATA_SOURCE_TCMKT);
                        put("surface", "tcmkt_activity_first");
                    }});
                    if(firId!=null){
                        int number=Integer.valueOf(firId.get("uuid").toString());
                        FirId= ComUtils.getLocalTrmSeqNum("hdsy",number);
                    }else{
                        FirId=ComUtils.getLocalTrmSeqNum("hdsy",0);
                    }
                    first.putAll(commonInsertParms);
                    first.put("FirId",FirId);
                    first.put("ActType",4);
                    activityMapper.AddActivityFirst(first);
                }

                //活动-选择的房源
                List<Map<String, Object>> AlreadyHousing = (List<Map<String, Object>>) params.get("AlreadyHousing");
                for(Map<String, Object> map:AlreadyHousing){
                    map.putAll(commonInsertParms);
                    activityMapper.AddActivityHousing(map);
                }
                result=true;
            } catch (NumberFormatException e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
        finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 功能描述: 
     * 获取已创建活动
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/2/15 21:48
     */
    public List<Map<String,Object>>getActivityList(Map<String,Object>params){
        List<Map<String,Object>>getActivityList=activityMapper.getActivityList(params);
        return getActivityList;
    }

    /**
     * 功能描述: 
     * 获取已创建活动总数
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/2/15 21:49
     */
    public Integer getActivityListCount(Map<String,Object>params){
        Integer getActivityListCount=activityMapper.getActivityListCount(params);
        return getActivityListCount;
    }

    /**
     * 功能描述: 
     * 根据编号获取活动详情
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/2/16 11:47
     */
    public Map<String,Object>getActivity(Map<String,Object>params){
        Map<String,Object>getActivity=activityMapper.getActivity(params);
        if(getActivity.get("IfLong").equals(0)){
            getActivity.put("IfLong",false);
            getActivity.put("IfLongDis",false);
        }else{
            getActivity.put("IfLong",true);
            getActivity.put("IfLongDis",true);
        }
        if(getActivity.get("IfCoupon").equals(0)){
            getActivity.put("IfCoupon",false);
        }else{
            getActivity.put("IfCoupon",true);
        }
        if(getActivity.get("PayType").equals(0)){
            getActivity.put("PayTypeDisabled",false);
        }else{
            getActivity.put("PayTypeDisabled",true);
        }
        getActivity.put("PayType",getActivity.get("PayType").toString());
        getActivity.put("Type",getActivity.get("Type").toString());
        //获取折扣活动列表
        List<Map<String,Object>>getActivityFullList=activityMapper.getActivityFullList(params);
        if(getActivityFullList.size()>0){
            //false 打几折FulOff   true减金额FulMoney
            for(Map<String,Object> map:getActivityFullList){
                map.put("checkbox",true);
                if(!FieldCheckUtil.isMapFieldNotNull(map,new String[]{"FulMoney"})){
//                    map.put("radioDis",false);
                    map.put("radio","0");
                }
                if(!FieldCheckUtil.isMapFieldNotNull(map,new String[]{"FulOff"})){
//                    map.put("radioDis",true);
                    map.put("radio","1");
                }
            }
        }
        //获取周期活动列表
        List<Map<String,Object>>getActivityPayList=activityMapper.getActivityPayList(params);
        if(getActivityPayList.size()>0){
            //false 打几折FulOff   true减金额FulMoney
            for(Map<String,Object> map:getActivityPayList){
                map.put("checkbox",true);
                if(!FieldCheckUtil.isMapFieldNotNull(map,new String[]{"FulMoney"})){
//                    map.put("radioDis",false);
                    map.put("radio","0");
                }
                if(!FieldCheckUtil.isMapFieldNotNull(map,new String[]{"FulOff"})){
//                    map.put("radioDis",true);
                    map.put("radio","1");
                }
            }
        }
        //获取满送活动
        Map<String,Object>getActivitySendMap=activityMapper.getActivitySendMap(params);
        if(getActivitySendMap!=null && getActivitySendMap.size()>0){
            getActivitySendMap.put("checkbox",true);
        }
        //获取首月活动
        Map<String,Object>getActivityFirstMap=activityMapper.getActivityFirstMap(params);
        if(getActivityFirstMap!=null && getActivityFirstMap.size()>0){
            getActivityFirstMap.put("checkbox",true);
            if(!FieldCheckUtil.isMapFieldNotNull(getActivityFirstMap,new String[]{"FulMoney"})){
                getActivityFirstMap.put("radioDis",false);
                getActivityFirstMap.put("radio","0");
            }
            if(!FieldCheckUtil.isMapFieldNotNull(getActivityFirstMap,new String[]{"FulOff"})){
                getActivityFirstMap.put("radioDis",true);
                getActivityFirstMap.put("radio","1");
            }
        }
        //获取活动绑定的房源
        List<Map<String,Object>>getActivityHousingList=activityMapper.getActivityHousingList(params);
        getActivity.put("full",getActivityFullList);
        getActivity.put("pay",getActivityPayList);
        getActivity.put("send",getActivitySendMap);
        getActivity.put("first",getActivityFirstMap);
        getActivity.put("AlreadyHousing",getActivityHousingList);

        return getActivity;
    }

    /**
     * 功能描述: 
     * 根据活动编号修改活动
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/2/25 18:26
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean UpActivity(Map<String,Object>params){
        boolean resule=false;
        try {
            //修改处理
            Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
            commonUpdateParms.put("by", MapUtils.getInteger(params, "userId"));//操作人
            commonUpdateParms.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            commonUpdateParms.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonUpdateParms(commonUpdateParms);

            params.putAll(commonUpdateParms);
            //修改活动主表
            activityMapper.UpActivity(params);
            //删除活动已选房源，然后新增
            activityMapper.DelActivityHousingList(params);
            //所有新增处理
            Map<String,Object>commonInsertParms=new HashMap<String,Object>();
            commonInsertParms.put("by", ContextUtils.getUserId());//操作人
            commonInsertParms.put("ActId",params.get("ActId"));//活动主表编号
            commonInsertParms.put("term", "2");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            commonInsertParms.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(commonInsertParms);
            //活动-选择的房源
            List<Map<String, Object>> AlreadyHousing = (List<Map<String, Object>>) params.get("AlreadyHousing");
            for(Map<String, Object> map:AlreadyHousing){
                map.putAll(commonInsertParms);
                activityMapper.AddActivityHousing(map);
            }
            resule=true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resule;
    }

    /**
     * 功能描述: 
     * 活动重新启用或者停用
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/2/25 20:12
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean UpActivityStatus(Map<String,Object>params){
        boolean result=false;
        try {
            //修改处理
            Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
            commonUpdateParms.put("by", MapUtils.getInteger(params, "userId"));//操作人
            commonUpdateParms.put("term", "8");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            commonUpdateParms.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonUpdateParms(commonUpdateParms);
            params.putAll(commonUpdateParms);
            activityMapper.UpActivityStatus(params);
            result=true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 功能描述:
     * 根据活动编号修改活动
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/2/25 18:26
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean UpActivityTime(Map<String,Object>params){
        boolean resule=false;
        try {
            //修改处理
            Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
            commonUpdateParms.put("by", MapUtils.getInteger(params, "userId"));//操作人
            commonUpdateParms.put("term", "8");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
            commonUpdateParms.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonUpdateParms(commonUpdateParms);

            params.putAll(commonUpdateParms);
            params.put("Status","0");
            //修改活动主表
            activityMapper.UpActivityTime(params);
            resule=true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return resule;
    }
}
